// 导入koa
const Koa = require('koa')
const Router = require('koa-Router')
const path = require('path')
const fs = require('fs')
const jwt = require('jsonwebtoken');
const bodyparser = require('koa-bodyparser')
const { WebSocketServer } = require('ws');
const listdata=require('./database/section.json')
// 创建koa服务器

const app = new Koa()
const router = new Router()
// 导入cors跨域
const cors = require('koa-cors')
// 导入获取post数据
const {
  koaBody
} = require('koa-body')
// const {
//   fileURLToPath
// } = require('url')

// 使用中间件

app.use(koaBody())
app.use(cors())
app.use(bodyparser())
app.use(router)


// 聊天室
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
    ws.on('error', console.error);
    ws.on('message', function message(data) {
        console.log('received: %s', data);

        let response;
        const message = data.toString();

        // 根据不同的输入返回不同的内容
        if (message.includes('你好')) {
            response = '你好！有什么我可以帮您的吗？';
        } else if (message.includes('天气')) {
            response = '今天天气晴朗，非常适合外出！';
        } else if (message.includes('帮助')) {
            response = '当然！请告诉我您需要什么帮助。';
        } else {
            response = '抱歉，我不太明白您的问题。';
        }

        ws.send(response);
    });
});



// // 登录




let arr=[
{
 id:1,
 username:'15902770321',
 password:'123456',
 name:'Shine',
 img:'https://img2.baidu.com/it/u=2145276599,4283233498&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800'
},
 {
id:2,
username:'15072282778',
 password:'123456',
 name:'九儿',
 img:'https://img0.baidu.com/it/u=1121791498,3395223981&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800'
}
]



// // 开始处理请求
// // 登录
router.post('/api/login',ctx=>{
let {username,password}=ctx.request.body
let flag=arr.find(item=>item.username===username && item.password===password)
if(flag){
const token=jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
ctx.body={
code:200,
msg:'登录成功',
token,
name:flag.name,
img:flag.img
}
}else{
 ctx.body={
 code:404,
msg:'登录失败'
}
}
})



// 首页tab切换数据
router.get('/api/list',ctx=>{
    ctx.body={
        code:200,
        msg:'请求成功',
        data:listdata
    }
})


// 监听端口号
app.listen(3000, () => {
  console.log('server is running at http://localhost:3000')
})